<?php

namespace app\utils;


use think\Image;
use Yii;
use yii\helpers\Html;

class BaseUtils {

    const SCALE = 2;

    public static function generateUUid($n = 11, $uid = NULL, $data = NULL) {
        $uuid = substr(time(), 3, 2);
        if (!empty($uid)) {
            $m = substr(md5($uid . time()), 8, 4);
            $str = substr(implode(NULL, array_map('ord', str_split($m))), 3, 3);
            $uuid .= $str;
        }

        if (!empty($data)) {
            $m = substr(md5($data . time()), 8, 4);
            $str = substr(implode(NULL, array_map('ord', str_split($m))), 3, 3);
            $uuid .= $str;
        }

        if (strlen($uuid) < $n) {
            $n1 = 12 - strlen($uuid);
            $tmp = '';
            $max = str_pad($tmp, $n1, 9);
            $min = str_pad($tmp, $n1, 1);
            $uuid .= mt_rand($min, $max);
        }
        return substr($uuid, 0, $n);
    }

    public static function isValid($phone) {
        return preg_match('/^(1\d{10})$/', $phone);
    }

    public static function hidePhone($phone) {
        return substr_replace($phone, '****', 3, 4);
    }

    public static function getClientIp() {
        $ip = '0.0.0.0';
        if (isset($_SERVER['HTTP_X_REAL_IP'])) {
            $ip = trim($_SERVER['HTTP_X_REAL_IP']);
        } else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $tmp = array_slice($arr, -1, 1);
            $ip = trim($tmp[0]);
        } else if (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return sprintf("%u", ip2long($ip));
    }

    public static function encodeIp($ip) {
        return sprintf("%u", ip2long($ip));
    }

    public static function decodeIp($ip) {
        return long2ip($ip);
    }

    public static function is_writable_dir($dir) {
        self::mkdir($dir);
        if ($fp = @fopen("{$dir}/test.txt", 'w')) {
            @fclose($fp);
            @unlink("{$dir}/test.txt");
            return TRUE;
        }
        return FALSE;
    }

    public static function mkdir($dir) {
        if (!is_dir($dir)) {
            self::mkdir(dirname($dir));
            umask(0);
            return @mkdir($dir);
        }
        return FALSE;
    }

    public static function formatImage($avatar) {
        if (!empty($avatar) && strpos($avatar, 'http') === FALSE) {
            $avatar = \Yii::$app->request->hostInfo . '/' . trim($avatar, '/');
        }
        return $avatar;
    }

    public static function getAvatar($avatar = NULL) {
        $default = '/images/my-avator.jpg';
        if (empty($avatar) && NULL !== $default) {
            return Yii::getAlias('@assets') . $default;
        }
        return static::formatImage($avatar);
    }

    public static function formatTime($time) {
        $t = time() - $time;
        $f = array(
            '86400' => '天',
            '3600' => '小时',
            '60' => '分钟',
            '1' => '秒'
        );
        foreach ($f as $k => $v)
            if (0 != $c = floor($t / (int)$k))
                return $c . $v . '前';
        return date('m-d', $time);
    }

    public static function strLen($str) {
        preg_match_all("/./us", $str, $matches);
        return count(current($matches));
    }

    public static function watermark($file) {
        if (!is_file($file)) {
            return;
        }
        $watermarkImage = \Yii::getAlias('@webroot/assets/web/images/watermark.png');
        $image = Image::open($file);
        $image->water($watermarkImage)->save($file);
    }

    public static function thumb($file, $width, $height) {
        if (!is_file($file)) {
            return;
        }
        $image = Image::open($file);
        $image->thumb($width, $height)->save($file, NULL, 95);
    }

    public static function arrayToImage($items, $options = ['data-preview-src' => "", 'data-preview-group' => '4']) {
        $data = [];
        foreach ($items as $item) {
            $data[] = Html::a(Html::img($item, $options), $item, ['target' => '_blank', 'style' => 'display: block; ']);
        }
        return join("\n", $data);
    }


    public static function subString($str, $length, $start = 0, $suffix = '...', $charset = 'utf-8') {
        if (function_exists('mb_substr')) {
            return mb_strlen($str, $charset) > $length ? (mb_substr($str, $start, $length, $charset) . $suffix) : $str;
        } elseif (function_exists('iconv_substr')) {
            return iconv_strlen($str, $charset) > $length ? (iconv_substr($str, $start, $length, $charset) . $suffix) : $str;
        }
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
        return $slice . $suffix;
    }

    public static function convertText($string, $length = 0) {
        $string = strip_tags($string);
        $string = str_replace(array('&nbsp;', "\r", "\n", "\t", "　"), '', $string);
        $string = trim($string);
        if ($length > 0) {
            $string = self::subString($string, $length);
        }
        return $string;
    }
}